package com.lemon.smartsafety.ui.activity.baidu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.baidu.BaiduMapEvent;
import com.lemon.smartsafety.entity.baidu.BaiduMapResultEvent;
import com.lemon.smartsafety.mode.adapter.BaiduAddressMode;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.adapter.baidu.BaiduAddressAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.NearbySearchUtil;
import com.lemon.smartsafety.utils.PoiNearbySearchUtil;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class LemonBaiduActivity extends NewBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.mapView)
    MapView mMapView;
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.txt_check)
    TextView txtCheck;
    @Bind(R.id.txt_name)
    TextView txtName;
    @Bind(R.id.txt_content)
    TextView txtContent;
    @Bind(R.id.lineAll)
    RelativeLayout lineAll;


    private BaiduAddressAdapter baiduAddressAdapter;
    private List<BaiduAddressMode> mList;


    private NearbySearchUtil nearbySearchUtil;
    private LocationUtil loacationUtil;
    private PoiNearbySearchUtil poiNearbySearch;
    //百度地图参数
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BaiduMap mBaiduMap;
    private BaiduSDKReceiver mBaiduReceiver;

    private BaiduAddressMode searchMode = null;

    //城市内检索 的城市
    private String strCity = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void getBundleArgs() {

    }

    @Override
    protected int getContentViewId() {
        SDKInitializer.initialize(getApplicationContext());
        return R.layout.activity_lemon_baidu;
    }

    @Override
    protected void initTitleView() {

    }

    @Override
    protected void initView() {

        mList = new ArrayList<>();
        baiduAddressAdapter = new BaiduAddressAdapter(mActivity, mList);
        listView.setAdapter(baiduAddressAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showMap(mList.get(position).getLatLng().latitude, mList.get(position).getLatLng().longitude);
                current_page = 1;
                searchMode = mList.get(position);
                changeSearch();

            }
        });
        listView.setScrollBottomListener(new ListRefreshView.ScrollBottomListener() {
            @Override
            public void scrollBottom() {
                LogUtils.LOGE("上啦加载更多");
                if (searchMode == null) {
                    return;
                }
                bPutHttp = true;

                showUpLoad(true, listView);
                current_page = current_page + 1;
                searchPoi(searchMode.getLatLng(), searchMode.getSearchName());
            }
        });

        initMap();

    }

    /**
     * 改变搜索地址
     */
    private void changeSearch() {
        initAddress();
        if (CommonUtil.strIsEmpty(searchMode.getSearchName())) {
            poiNearbySearch.getLatLngLocation(searchMode.getLatLng(), new PoiNearbySearchUtil.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {
                    BaiduResult baiduResult = JsonUtils.fromJson(result, BaiduResult.class);
                    searchMode.setSearchName(baiduResult.getResult().getAddressComponent().getStreet());
                    searchMode.setCountry(baiduResult.getResult().getAddressComponent().getCountry());
                    if (CommonUtil.strIsEmpty(searchMode.getCity())) {
                        searchMode.setCity(baiduResult.getResult().getAddressComponent().getCity());
                    }
                    searchPoi(searchMode.getLatLng(), searchMode.getSearchName());
                }
            });
        } else {
            searchPoi(searchMode.getLatLng(), searchMode.getSearchName());
        }
    }


    private void initAddress() {
        lineAll.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.white_map));
        txtName.setText(searchMode.getName().replace(searchMode.getCountry(), ""));
        txtContent.setText(searchMode.getContent());
        txtCheck.setVisibility(View.VISIBLE);

    }


    @Override
    protected void initHttp() {

    }

    @Override
    protected void initList() {

    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        try {
            mMapView.onDestroy();
            poiNearbySearch.onDestroy();
            nearbySearchUtil.onDestroy();
            loacationUtil.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     /*   super.onCreateOptionsMenu(menu);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return menuResult;
*/
        getMenuInflater().inflate(R.menu.menu_search, menu);
        getMenuInflater().inflate(R.menu.menu_choose, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_search) {
            //搜索
            LoggerHelper.error(getClass(), "搜索");

            Intent intent = new Intent(mActivity, LemonBaiduSearchActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(BundleKey.MAP_SEARCH, searchMode.getCity());
            intent.putExtras(bundle);
            startActivity(intent);
        }
        if (item.getItemId() == R.id.action_sure) {
            //确定
            LoggerHelper.error(getClass(), "确定");

            if (searchMode != null) {
                AppService.getBus().post(new BaiduMapResultEvent(searchMode));
                mActivity.finish();
            }

        }
        return super.onOptionsItemSelected(item);
    }


    @Subscribe
    public void onEventMainThread(BaiduMapEvent event) {

        if (event.getSearchMode() != null) {
            searchMode = event.getSearchMode();
            strCity = searchMode.getCity();
            showMap(searchMode.getLatLng().latitude, searchMode.getLatLng().longitude);
            current_page = 1;
            changeSearch();
        }


    }


    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播  正常不需要
     */
    public class BaiduSDKReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            String st1 = "网络出错";
            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {

                String st2 = "key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置";
                ToastUtils.toastMsg(st2);
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                ToastUtils.toastMsg(st1);
            }
        }
    }


    /**
     * 初始化个人位置 百度地图
     */
    private void initMap() {

        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
        //mMapView.setLongClickable(true);

        //初始化地图的三个工具类
        nearbySearchUtil = new NearbySearchUtil(mActivity);
        poiNearbySearch = new PoiNearbySearchUtil(mActivity);
        loacationUtil = new LocationUtil(mActivity);


        loacationUtil.showLocationDialog(new LocationUtil.CallBackInterface() {
            @Override
            public void callBackFunction() {
                mActivity.finish();
            }
        });
        loacationUtil.getLoacation(new LocationUtil.CallBackInterface() {
            @Override
            public void callBackFunction() {
                if(loacationUtil.getMlocation()==null){
                    return;
                }

                loacationUtil.dissmissLocationDialog();
                LatLng locationP = new LatLng(loacationUtil.getMlocation().getLatitude(), loacationUtil.getMlocation().getLongitude());
                mMapView = new MapView(mActivity,
                        new BaiduMapOptions().mapStatus(new MapStatus.Builder()
                                .target(locationP).build()));

                showMap(loacationUtil.getMlocation().getLatitude(), loacationUtil.getMlocation().getLongitude());
                strCity = loacationUtil.getMlocation().getCity();

                searchMode = new BaiduAddressMode(locationP, loacationUtil.getMlocation().getStreet());
                searchMode.setCity(strCity);
                searchMode.setCountry(loacationUtil.getMlocation().getCountry());
                searchMode.setName(loacationUtil.getMlocation().getAddrStr());
                searchMode.setContent(loacationUtil.getMlocation().getSemaAptag());
                searchMode.setAddress(loacationUtil.getMlocation().getAddrStr());
                searchPoi(searchMode.getLatLng(), searchMode.getSearchName());
                initAddress();
            }
        });


/*        // 注册 SDK 广播监听者
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mBaiduReceiver = new BaiduSDKReceiver();
        registerReceiver(mBaiduReceiver, iFilter);*/

    }


    private void showMap(double latitude, double longtitude) {
        //清楚覆盖物
        mBaiduMap.clear();

        LatLng llA = new LatLng(latitude, longtitude);
        CoordinateConverter converter = new CoordinateConverter();
        converter.coord(llA);
        converter.from(CoordinateConverter.CoordType.COMMON);
        LatLng convertLatLng = converter.convert();
        OverlayOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_address_location))
                .zIndex(4).draggable(true);
        mBaiduMap.addOverlay(ooA);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 17.0f);
        mBaiduMap.animateMapStatus(u);

    }


    /**
     * 搜索
     *
     * @param p
     */
    private void searchPoi(LatLng p, String keyWord) {

        poiNearbySearch.setLoadIndex(current_page - 1);
        poiNearbySearch.searchNearbyProcess(p, keyWord, new PoiNearbySearchUtil.CallBackInterface() {
            @Override
            public void callBackFunction(boolean isSuccess) {

                showUpLoad(false, listView);
                if (!isSuccess) {
                    bPutHttp = false;
                    ToastUtil.show("未找到更多位置信息");
                    return;
                }

                if (CommonUtil.listIsEmpty(poiNearbySearch.getPoiResult().getAllPoi())) {
                    return;
                }
                if (current_page == 1) {
                    LogUtils.LOGE("清空列表");
                    mList.clear();
                    baiduAddressAdapter.notifyDataSetChanged();
                }

                for (int i = 0; i < poiNearbySearch.getPoiResult().getAllPoi().size(); i++) {
                    BaiduAddressMode baiduAddressMode = new BaiduAddressMode(poiNearbySearch.getPoiResult().getAllPoi().get(i).name, poiNearbySearch.getPoiResult().getAllPoi().get(i).address, poiNearbySearch.getPoiResult().getAllPoi().get(i).location);
                    baiduAddressMode.setUid(poiNearbySearch.getPoiResult().getAllPoi().get(i).uid);
                    baiduAddressMode.setAddress(poiNearbySearch.getPoiResult().getAllPoi().get(i).address);
                    baiduAddressMode.setCity(poiNearbySearch.getPoiResult().getAllPoi().get(i).city);
                    mList.add(baiduAddressMode);
                }
                baiduAddressAdapter.notifyDataSetChanged();

                if (mList.size() % 10 == 0) {
                    listView.setIsload(true);
                } else {
                    listView.setIsload(false);
                }

                if (current_page == 1) {
                    listView.setSelection(0);
                }

            }
        });
    }


}
